package com.fs.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fs.common.constant.CacheConstants;
import com.fs.common.core.pojo.SysConfig;
import com.fs.common.util.RedisCache;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;

@Service
public class SysConfigServiceImpl implements ISysConfigService {
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedisCache redisCache;


    @PostConstruct  //标记在方法上, 当这个bean创建完成,自动执行这个注解标记方法,要求这个方法无参  类似 init-method配置
    public void  init(){
        loadingConfigCache();
    }


/**
 * 通过mapper查询出sys_config表中的所有数据，将其中的配置相关信息存入redis中
 * */
    public void loadingConfigCache() {
        List<SysConfig> sysConfigList=sysConfigMapper.selectList(null);
        sysConfigList.forEach((sysConfig)->{
            redisCache.setCacheObject(getCacheKey(sysConfig.getConfigKey()),sysConfig.getConfigValue());
        });
    }

//    存放到redis中的key除了数据库中的数据外，在前面还需要加上一个前缀
    private String getCacheKey(String configKey){
        return CacheConstants.SYS_CONFIG_KEY+configKey;
    }

/**
 *
 * */
    public boolean selectCaptchaEnabled() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if(StrUtil.isBlank(captchaOnOff)){ //是空
            return true; //默认开启
        }
        return Convert.toBool(captchaOnOff);
    }

    public String selectConfigByKey(String configKey) {
        String configValue=Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));//通过configkey从redis中获取到响应的值
        if(StrUtil.isNotBlank(configValue)){
            return configValue;
        }else {
            LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysConfig::getConfigKey, configKey);
            SysConfig sysConfig = sysConfigMapper.selectOne(queryWrapper);
            if (!Objects.isNull(sysConfig)) {
                redisCache.setCacheObject(getCacheKey(configKey), sysConfig.getConfigValue());
                return sysConfig.getConfigValue();
            }
            return null;
        }
    }



}
